

import { ipcRenderer } from "electron";
import fs from 'fs';
import { ipcMain,webContents   } from 'electron';   
const path = process.env.NODE_ENV === 'development'
  ? 'db.json'
  : `file://${__dirname}/db.json`
// 读取文件
export const readdbs = (args) => { 
  return new Promise((resolve, inject) => {
    fs.readFile(`${path}`, (err, data) => {  
      if (err) {
        inject(false)
      }
      try{
        resolve(data.toString());
      }catch(err){
        resolve(`${data}`);
      } 
    })
  })
}
// readdbs().then(res=>{
//    console.log(res);
// }) 
// 每天计划只能写一条，一条200字
// 创建+更新 时间格式yyyy-mm-dd
export const createNote = (time, note) => {
  return new Promise((resolve, inject) => {
    readdbs('db').then(res => {
      if (res) {
        let jsonstr = typeof res == 'object'?res:JSON.parse(res);
        jsonstr[time] = note;
        fs.writeFile(path, JSON.stringify(jsonstr), (err) => {
          if (err){
            resolve(false)
          }else{
            resolve(JSON.stringify({[time]:note}));
          }
        });
      }
    })
  })
}
// 移除
export const deleteNote = (time) => {
  return new Promise((resolve, inject) => {
    readdbs('db').then(res => {
      if (res) {
        let jsonstr = typeof res == 'object'?res:JSON.parse(res);
        delete jsonstr[time]
        fs.writeFile(path, JSON.stringify(jsonstr), (err) => {
          if (err){
            resolve(false)
          }else{
            resolve(true)
          } 
        });
      }
    })
  })
}

 



// 开启子线程，通过子线程对数据库进行初始化，或者获取初始化数据，
 export const inits = (cbs)=>{
 
  readdbs('db').then(res => {  
 
    cbs(res)
  },(err)=>{
    cbs('');
  })  
 }


window.ipcRenderer = ipcRenderer
 


 